﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Net;

namespace Game.Server.Socket
{
    public class AllowDomain
    {
        private TcpListener Server;
        private AsyncCallback callback;
        private bool islisten = false;

        public AllowDomain()
        {

        }

        public void Start()
        {
            this.Server = new TcpListener(844);
            this.Server.Start();
            this.callback = new AsyncCallback(this.OnConnectionEvent);
            this.islisten = true;
            this.Server.BeginAcceptSocket(this.callback, null);
        }

        public void Close()
        {
            this.islisten = false;
            this.Server.Stop();
        }

        private void OnConnectionEvent(IAsyncResult syn)
        {
            if (this.islisten)
            {
                SocketError error;
                System.Net.Sockets.Socket conn = this.Server.EndAcceptSocket(syn);

                byte[] buffer = new byte[1024];
                int len = conn.Receive(buffer, 0, 1024, SocketFlags.None, out error);
                if (error == SocketError.Success)
                {
                    string s = Encoding.Default.GetString(buffer, 0, len);
                    if (s == "<policy-file-request/>\0")
                    {
                        buffer = Encoding.Default.GetBytes("<cross-domain-policy><site-control permitted-cross-domain-policies=\"all\" /><allow-access-from domain=\"*\" to-ports=\"*\"/><allow-http-request-headers-from domain=\"*\" headers=\"*\"/></cross-domain-policy>\0");
                        conn.Send(buffer);
                    }
                }
                conn.Close();
                if (this.islisten)
                    this.Server.BeginAcceptSocket(this.OnConnectionEvent, null);
            }
        }
    }
}
